package com.davy.gridpoint.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * 描述  限制小数点后输入位数
 * <p>
 * 默认限制小数点2位
 * <p>
 * 默认第一位输入小数点时，转换为0.
 * <p>
 * 如果起始位置为0,且第二位跟的不是".",则无法后续输入
 */
public class NumberDecimalFilter {
    private EditText priceEdit;

    public NumberDecimalFilter(EditText priceEdit) {
        this.priceEdit = priceEdit;
        priceEdit.addTextChangedListener(textWatcher);
    }

    public TextWatcher setTextWatcher() {
        return textWatcher;
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                    s = s.toString().subSequence(0,
                            s.toString().indexOf(".") + 3);
                    priceEdit.setText(s);
                    priceEdit.setSelection(s.length());
                }
            }
            if (s.toString().trim().substring(0).equals(".")) {
                s = "0" + s;
                priceEdit.setText(s);
                priceEdit.setSelection(2);
            }
            if (s.toString().startsWith("0")
                    && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    priceEdit.setText(s.subSequence(1, 2));
                    priceEdit.setSelection(1);
                    return;
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };
}
